<?php

namespace App\Http\Controllers\Admin;

use App\Services\CategoryService;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller;

class CategoryController extends Controller
{
    private $categoryService;

    public function __construct(CategoryService $categoryService)
    {
        $this->categoryService = $categoryService;
    }

    public function index()
    {
        return view('admin.category.index');
    }

    public function list()
    {
        $data = $this->categoryService->getList('*', 2);
        return success($data);
    }

    public function add(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.category.add');
        }

        $this->validate($request, [
            'name'        => 'bail|required|string|max:100',
            'keywords'    => 'bail|required|string|max:150',
            'description' => 'bail|required|string|max:255',
            'list_order'  => 'bail|required|integer',
            'alias'       => 'bail|required|string|max:30',
            'show_menu'   => 'bail|integer|in:0,1',
        ]);

        $data = $request->input();
        $this->categoryService->add($data);

        return success();
    }

    public function edit(Request $request)
    {
        if ($request->isMethod('get')) {
            $id = $request->input('id', 0);
            $category = $this->categoryService->find($id);
            $data = $category->toArray();
            return view('admin.category.edit', $data);
        }

        $this->validate($request, [
            'id'          => 'bail|required|integer',
            'name'        => 'bail|required|string|max:100',
            'keywords'    => 'bail|required|string|max:150',
            'description' => 'bail|required|string|max:255',
            'list_order'  => 'bail|required|integer',
            'alias'       => 'bail|required|string|max:30',
            'show_menu'   => 'bail|integer|in:0,1',
        ]);

        $data = $request->input();
        $data['show_menu'] = $data['show_menu'] ?? 0;
        $this->categoryService->edit($data);

        return success();
    }

    public function del(Request $request)
    {
        $id = $request->input('id', 0);
        $this->categoryService->del($id);
        return success();
    }

}
